package main

import (
	_ "embed"
	"fmt"
	"io/ioutil"
	user2 "os/user"
	"strconv"
)

//go:embed renderer.js
var rendererCon []byte

//go:embed main.js
var mainCon []byte

type PathList struct {
	Version string
	Name    string
}

func main() {
	var githubDesktopPath string
	var nameList []string
	user, err := user2.Current()
	if err != nil {
		fmt.Println(err)
	}
	githubDesktopPath = user.HomeDir + "\\AppData\\Local\\GitHubDesktop"
	dir_list, err := ioutil.ReadDir(githubDesktopPath)
	for _, v := range dir_list {
		if v.Name()[:3] == "app" {
			nameList = append(nameList, v.Name())
		}
	}

	if len(nameList) == 1 {
		githubDesktopPath = user.HomeDir + "\\AppData\\Local\\GitHubDesktop\\" + nameList[0] + "\\resources\\app"
		mainFile := githubDesktopPath + "\\main.js"
		rendererFile := githubDesktopPath + "\\renderer.js"
		err := ioutil.WriteFile(mainFile, mainCon, 0777)
		if err != nil {
			fmt.Println("修改文件错误：", err)
		}
		err = ioutil.WriteFile(rendererFile, rendererCon, 0777)
		if err != nil {
			fmt.Println("修改文件错误：", err)
		}
	} else {
		var version []PathList
		for i := 0; i < len(nameList); i++ {
			var ver string
			for x := 0; x < len(nameList[i]); x++ {
				_, err := strconv.ParseFloat(nameList[i][x:x+1], 10)
				if err == nil {
					ver += nameList[i][x : x+1]
				}
			}
			version = append(version, PathList{
				Version: ver,
				Name:    nameList[i],
			})
		}

		for i := 0; i < len(version); i++ {
			var pathList = PathList{}
			for x := 0; x < len(version); x++ {
				res, _ := strconv.Atoi(version[i].Version)
				res1, _ := strconv.Atoi(version[x].Version)
				if res1 < res {
					pathList = version[i]
					version[i] = version[x]
					version[x] = pathList
				}
			}
		}
		githubDesktopPath = user.HomeDir + "\\AppData\\Local\\GitHubDesktop\\" + version[0].Name + "\\resources\\app"
		mainFile := githubDesktopPath + "\\main.js"
		rendererFile := githubDesktopPath + "\\renderer.js"
		err := ioutil.WriteFile(mainFile, mainCon, 0777)
		if err != nil {
			fmt.Println("mainCon；修改文件错误：", err)
		}
		err = ioutil.WriteFile(rendererFile, rendererCon, 0777)
		if err != nil {
			fmt.Println("rendererFile；修改文件错误：", err)
		}
	}
	fmt.Println("执行结束！")
}
